package tecpointbenchmark.model.modules;

import java.util.Date;

import tecpointbenchmark.model.dto.ResultDTO;

/**
 * 
 * @author Linus & Patrik
 * Calculates as many times as possible and saves the number of primes found in the resultDTO 
 */
public class SingleThreadIntegerModule extends BenchmarkModule {

    /**
     * Creates a new object with the resultDTO to save the result into.
     * @param r The result to where the benchmark is saving his info.
     */
    public SingleThreadIntegerModule(ResultDTO r) {
        super(r);
        super.setModuleName("CPU Integer");
        super.setShortDescription("Calculates as many primes as possible");
        super.setLongDescription("Calculates all primes, starting at 2, "
                + "going until aborted. The result is the number of primes found");
    }

    /*
     * Runs the benchmark
     */
    @Override
    public void runBenchmark() {
        // Fetch the result object
        ResultDTO result = super.getResult();

        // Allow benchmarking
        super.setContinueBenchmarking(true);

        result.setTime(new Date().getTime());

        // Set the result to ERROR(2)
        result.setNumber(2);

        // The boolean variable 'continueBenchmarking' will remain true until
        // the handler changes it's value.
        long primes = 0;
        int toBeChecked = 2;

        long start = System.currentTimeMillis();

        while (super.getContinueBenchmarking()) {
            boolean isPrime = true;

            for (int i = 2; i < toBeChecked; i++) {
                if (toBeChecked % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                primes++;
            }
            toBeChecked++;
        }

        long end = System.currentTimeMillis();
        float time = (end - start) / 1000f;

        result.setMessage("Number of primes found: " + primes);
        result.setPoints((int) (primes/9 * (5 / time)));
        if (tecpointbenchmark.startup.Main.debug) {
            System.out.println(result.getMessage());
            System.out.println("Module closing.");
        }
    }
}
